package com.another.common.utils.common;

import com.alibaba.fastjson.JSON;
import com.another.common.utils.result.Result;
import com.another.common.utils.result.ResultEnum;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * @ Author      ：another.
 * @ Create Time ：14:05 2019/9/7
 * @ Description ：  Result 转换实体类
 */
public class ResultToObject {

    /**
     * Result转换对象
     * @param result
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T ObjectToClassService(Result result, Class<T> clazz) {
        if (result.getCode().equals(ResultEnum.ERROR.getCode())) {
            throw new MyException(ResultEnum.ERROR.getCode(), result.getMsg());
        } else {
            LinkedHashMap map = (LinkedHashMap)result.getData();
            if (EmptyUtil.isEmpty(result.getData())) {
                return null;
            } else {
                ObjectMapper mapper = new ObjectMapper();
                T res = mapper.convertValue(map, clazz);
                return res;
            }
        }
    }

    /**
     * Result转换List
     * @param result
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> List<T> ObjectToListService(Result result, Class<T> clazz) {
        if (result.getCode().equals(ResultEnum.ERROR.getCode())) {
            throw new MyException(ResultEnum.ERROR.getCode(), result.getMsg());
        } else {
            List<LinkedHashMap> mapList = (List)result.getData();
            if (EmptyUtil.isEmpty(result.getData())) {
                return null;
            } else {
                ObjectMapper mapper = new ObjectMapper();
                List<T> list = new ArrayList();
                Iterator var5 = mapList.iterator();

                while(var5.hasNext()) {
                    LinkedHashMap map = (LinkedHashMap)var5.next();
                    T res = mapper.convertValue(map, clazz);
                    list.add(res);
                }

                return list;
            }
        }
    }


    public static <T> T ObjectToClassLocal(Result result, Class<T> clazz) {
        if (result.getCode().equals(ResultEnum.ERROR.getCode())) {
            throw new MyException(ResultEnum.ERROR.getCode(), result.getMsg());
        } else {
            if (EmptyUtil.isEmpty(result.getData())) {
                return null;
            } else {
                T res = JSON.parseObject(JSON.toJSONString(result.getData()), clazz);
                return res;
            }
        }
    }

}
